Starting and stopping windows services

Author: DelphiFAQ.com
Homepage:  http://www.delphifaq.com

Category: System

{
The following two functions allow you to start or stop a Windows service - local
or on a remote computer:

ServiceStart and ServiceStop.

Use them as shown in the block at the end.
}

{ Thanks to Andrea Canu for pointing out a problem in this code (fixed now). }

program test;

uses
  WinSvc;

{sc-----------------------------------------------------------------------
  ServiceStart

  sMachine:
     machine name, ie: \\SERVER
     empty = local machine

  Purpose:
     start service
     return TRUE if successful
-----------------------------------------------------------------------sc}
function ServiceStart(sMachine, sService: String) : Boolean;
var
  schm,
  schs: SC_Handle;
  ss: TServiceStatus;
  psTemp: PChar;
  dwChkP: DWord;
begin
  ss.dwCurrentState := -1;
  schm := OpenSCManager(PChar(sMachine), nil, SC_MANAGER_CONNECT);
  if (schm>0) then
  begin
    schs := OpenService(schm, PChar(sService), SERVICE_START or
      SERVICE_QUERY_STATUS);
    if (schs>0) then
    begin
      psTemp := nil;
      if (StartService(schs, 0, psTemp)) then
        if (QueryServiceStatus(schs, ss)) then
          while (SERVICE_RUNNING<>ss.dwCurrentState) do
          begin
            dwChkP := ss.dwCheckPoint;
            Sleep(ss.dwWaitHint);
            if (not QueryServiceStatus(schs, ss)) then
              Break;
            if (ss.dwCheckPoint < dwChkP) then
              Break;
          end;
      CloseServiceHandle(schs);
    end;
    CloseServiceHandle(schm);
  end;
  Result := SERVICE_RUNNING=ss.dwCurrentState;
end;


{sc-----------------------------------------------------------------------
  ServiceStop

  Purpose:
   stop a service, parameters as in ServiceStart
-----------------------------------------------------------------------sc}
function ServiceStop(sMachine, sService: String) : Boolean;
var
  schm,
  schs: SC_Handle;
  ss: TServiceStatus;
  dwChkP: DWord;
begin
  schmtion ServiceStop(sMachine, sService: String) : Boolean;
var
  schm,
  schs: SC_Handle;
  ss: TServiceStatus;
  dwChkP: DWord;
begin
  schmtioOP or
      SERVICE_QUERY_STATUS);
    if (schs>0) then
    begin
      if (ControlService(schs, SERVICE_CONTROL_STOP, ss)) then
        if (QueryServiceStatus(schs, ss)) then
          while (SERVICE_STOPPED<>ss.dontrolService(schs, SERVICE_CONTROL_STOP, ss)) then
        if (QueryServiceStatus(schs, ss)) then
          while (SERVICE_STOPPED<>ss.dontrolService(schs, SERVICE_CONTROL_STOP, ss)) then
        if (QueryServiceStatus(schs, ss)) then
          while (
          end;
      CloseServiceHandle(schs);
    end;
    CloseServiceHandle(schm);
  end;
  Result := SERVICE_STOPPED=ss.dwCurrentState;
end;


begin
  if (ServiceStart('\\ComputerName', 'alerter')) then
  begin

    // ..
  end;
  if (ServiceStop('', 'alerter')) then
  begin

    // ..
  end;
end.
